<?php
/**
 * 清理重复设备
 * 根据设备型号合并重复设备，保留最近使用的一个
 */

$dataFile = __DIR__ . '/data/devices.json';
$historyFile = __DIR__ . '/data/history.json';

echo "==========================================================\n";
echo "  设备清理工具 - 删除重复设备\n";
echo "==========================================================\n\n";

// 读取设备列表
if (!file_exists($dataFile)) {
    echo "❌ 错误：devices.json 文件不存在\n";
    echo "   路径：$dataFile\n";
    exit(1);
}

$data = file_get_contents($dataFile);
$devices = json_decode($data, true);

if (!$devices || empty($devices)) {
    echo "ℹ️ 没有设备记录\n";
    exit(0);
}

echo "📊 当前设备总数：" . count($devices) . "\n\n";

// 按设备名分组
$grouped = [];
foreach ($devices as $deviceId => $device) {
    $deviceName = $device['device_name'] ?? 'Unknown Device';
    $deviceModel = $device['device_model'] ?? '';
    
    // 使用设备名+型号作为分组key
    $groupKey = trim("$deviceName $deviceModel");
    
    if (!isset($grouped[$groupKey])) {
        $grouped[$groupKey] = [];
    }
    
    $grouped[$groupKey][] = [
        'id' => $deviceId,
        'data' => $device,
        'last_seen' => $device['last_seen'] ?? '1970-01-01 00:00:00'
    ];
}

// 显示重复设备
echo "=== 重复设备检测 ===\n\n";
$duplicateGroups = [];
$totalDuplicates = 0;

foreach ($grouped as $name => $items) {
    if (count($items) > 1) {
        $duplicateGroups[$name] = $items;
        $totalDuplicates += (count($items) - 1);
        
        echo "📱 设备：$name\n";
        echo "   重复数量：" . count($items) . "\n";
        
        // 按最后在线时间排序
        usort($items, function($a, $b) {
            return strcmp($b['last_seen'], $a['last_seen']);
        });
        
        foreach ($items as $index => $item) {
            $marker = $index === 0 ? '✅ 最新' : '🗑️ 旧的';
            echo "   $marker ID: " . substr($item['id'], 0, 40) . "...\n";
            echo "        最后在线: {$item['last_seen']}\n";
        }
        echo "\n";
    }
}

if (empty($duplicateGroups)) {
    echo "✅ 没有发现重复设备\n";
    exit(0);
}

echo "⚠️ 总计发现 " . count($duplicateGroups) . " 组重复设备\n";
echo "   将删除 $totalDuplicates 个旧设备\n\n";

// 询问是否清理
echo "是否要删除重复设备（保留最新的）？ (yes/no): ";
$handle = fopen("php://stdin", "r");
$input = trim(fgets($handle));
fclose($handle);

if ($input !== 'yes' && $input !== 'y' && $input !== 'Y') {
    echo "\n❌ 已取消清理\n";
    exit(0);
}

echo "\n开始清理...\n\n";

// 执行清理
$cleanedDevices = [];
$removedCount = 0;

foreach ($grouped as $name => $items) {
    if (count($items) > 1) {
        // 按最后在线时间排序
        usort($items, function($a, $b) {
            return strcmp($b['last_seen'], $a['last_seen']);
        });
        
        // 保留第一个（最新的）
        $kept = $items[0];
        $cleanedDevices[$kept['id']] = $kept['data'];
        $removedCount += (count($items) - 1);
        
        echo "✅ $name\n";
        echo "   保留: " . substr($kept['id'], 0, 40) . "... ({$kept['last_seen']})\n";
        echo "   删除: " . (count($items) - 1) . " 个旧记录\n";
    } else {
        // 没有重复，直接保留
        $item = $items[0];
        $cleanedDevices[$item['id']] = $item['data'];
    }
}

// 备份原文件
$backupFile = $dataFile . '.backup_' . date('YmdHis');
copy($dataFile, $backupFile);
echo "\n📦 原文件已备份到：\n   $backupFile\n";

// 保存清理后的设备列表
$result = file_put_contents(
    $dataFile, 
    json_encode($cleanedDevices, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
);

if ($result === false) {
    echo "\n❌ 错误：无法写入文件\n";
    echo "   请检查目录权限\n";
    exit(1);
}

echo "\n==========================================================\n";
echo "✅ 清理完成！\n";
echo "==========================================================\n";
echo "删除设备数：$removedCount\n";
echo "保留设备数：" . count($cleanedDevices) . "\n";
echo "==========================================================\n";
?>

